package com.hxkj.client.service.taglib.directive;

import com.hxkj.client.service.ColumnServiceClient;
import com.hxkj.client.service.TagsServiceClient;
import com.hxkj.domain.context.EnvironmentContextHolder;
import com.hxkj.domain.po.Article;
import com.hxkj.domain.po.Column;
import com.hxkj.domain.po.Tags;
import com.hxkj.domain.po.WebsiteAddr;
import com.platform.common.domain.result.ResultPageStruct;
import com.platform.common.domain.to.PageTo;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;


/**
 * @ClassName PageInfoDirective tag和分类的分页标签
 * @Description TODO
 * @Author Mr.zheng
 * @Date 2018/8/21 11:18
 * @Version 1.0
 */
@Component
@Log4j
public class PageInfoDirective extends AbstractDirective {


    @Autowired
    private ColumnServiceClient columnServiceClient;

    @Autowired
    private TagsServiceClient tagsServiceClient;

    /**
     * 输入参数，分类ID
     */
    public static final String COLUMN_ID = "columnId";
    /**
     * 输入参数，站点ID
     */
    public static final String SITE_ID = "siteId";
    /**
     * 输入参数，tagsID
     */
    public static final String TAGS_ID = "tagsId";


    /**
     * 文章列表的分页数据
     */
    public static final String COLUMN_ARTICLE_LIST_PAGE = "pageInfo";


    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws
            TemplateException, IOException {
        try {
            //Mr.zheng:获取参数
            Long columnId = super.getLong(COLUMN_ID, params) == null ? (Long) getCustomAttrbute(env, "columnId") : super.getLong(COLUMN_ID, params);
            Long siteId = super.getLong(SITE_ID, params) == null ? (Long) getCustomAttrbute(env, SITE_ID) : super.getLong(SITE_ID, params);
            Long tagsId = super.getLong(TAGS_ID, params) == null ? (Long) getCustomAttrbute(env, "tagsId") : super.getLong(TAGS_ID, params);
            int pageNum = (Integer) getCustomAttrbute(env, "pageNum") == null ? 1 :
                    (Integer) getCustomAttrbute(env, "pageNum");
            String note = super.getNote(env);
            ResultPageStruct<Article> resultPageStruct;
            PageTo pageInfo = new PageTo();
            String path = "";
            if (columnId != null) {
                Column column = new Column();
                column.setColumnId(columnId);
                column.setSiteId(siteId);
                column = columnServiceClient.getColumn(column);
                if (column != null && StringUtils.isNotBlank(column.getManuscriptPath())) {
//                    path = "/"+FilenameUtils.getPath(column.getManuscriptPath());
                    path = column.getManuscriptPath();
//                    path = path + FilenameUtils.getBaseName(column.getManuscriptPath());
//                    path = column.getManuscriptPath().split(".")[0];
                }
                resultPageStruct = getArticleResultPageStruct(pageNum, column);
                pageInfo = resultPageStruct.getPageInfo();
                if (pageInfo.getPages() > column.getPageNum()) {
                    pageInfo.setPages(column.getPageNum());
                }
            }
            if (tagsId != null) {
                Tags tags = new Tags();
                tags.setTagsId(tagsId);
                tags.setSiteId(siteId);
                tags = tagsServiceClient.getTags(tags);
                if (tags != null && StringUtils.isNotBlank(tags.getManuscriptPath())) {
                    path = tags.getManuscriptPath().split("_")[0];
                }
                resultPageStruct = getArticleResultPageStructByTags(pageNum, tags);
                pageInfo = resultPageStruct.getPageInfo();
            }
            if (StringUtils.isNotBlank(note)) {
                WebsiteAddr websiteAddr = getWebSiteAddr(siteId);
                path = websiteAddr.getIpAdd() + path;
            }else{
                // 单页静态文件链接加上下文
                Map<String, Object> enviroment = EnvironmentContextHolder.getEnvironment();
                Map<Long, String> siteCtxMap = (Map<Long, String>) enviroment.get("siteCtxMap");
                String urlContext = siteCtxMap.get(siteId);
                if(StringUtils.isNotBlank(urlContext)) {
                    path = urlContext +"/"+ path;
                }
            }
            pageInfo.setCondition(path);
            if (tagsId == null && columnId == null) env.setVariable(COLUMN_ARTICLE_LIST_PAGE, null);
            else
                env.setVariable(COLUMN_ARTICLE_LIST_PAGE, DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(pageInfo));

            String userToken = super.getUserToken(env);
            Writer out = env.getOut();
            if (body != null) {
                body.render(env.getOut());

            } else {
                throw new RuntimeException("分类所在模板至少要加一个空格");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
